<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <!-- <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 订单表格</el-breadcrumb-item> -->
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-plus" class="mr10" @click="add">添加</el-button>
                <!-- <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button> -->
                <el-select v-model="select_cate" placeholder="筛选" class="handle-select mr10">
                    <el-option key="1" label="名称" value="name"></el-option>
                    <el-option key="2" label="分类" value="type"></el-option>
                    <el-option key="3" label="堂食价" value="price"></el-option>
                    <!-- <el-option key="1" label="外卖价" value="price"></el-option> -->
                    <el-option key="4" label="上架" value="up"></el-option>
                    <el-option key="5" label="下架" value="down"></el-option>
                </el-select>
                <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="search" @click="search">搜索</el-button>
            </div>
           <!--  <div >{{form.spec.spec}}</div> -->
            <el-table id="out-table" :data="data" border class="table" ref="multipleTable" @selection-change="handleSelectionChange">
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->

                <el-table-column prop="good_name" label="名称" align="center" width='100' show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="type_name" label="分类" align="center" width='100' show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="good_img" label="图片" align="center">
                <template slot-scope="scope">
                      <a :href="scope.row.good_img"><img :src="scope.row.good_img" style="width: 50px;height: 50px;"></a>
                  </template>
              </el-table-column>
                <el-table-column prop="good_content" label="简介" align="center" width="240" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="good_spec" label="规格" align="center"  width="200" :formatter="formatSpec" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div  v-for="(item,index) in scope.row.spec_info" style="text-align: left;">
                            <p slot="content" class="good_spec">
                                {{index+1}}.<span>{{item.set_name}}</span>:
                                <span v-for="i in item.info" >{{i.groom > 0 ? '(推荐)':''}}{{i.set_type_name}}<i v-if="i.add_price > 0">+¥{{i.add_price}}元</i>、</span>
                            </p>                       
                        </div>
                    </template>
                </el-table-column>

                <!-- <el-table-column label="价格" align="center"> -->
                     <el-table-column prop="good_price" label="堂食价" align="center" width="150">
                    </el-table-column>
                   <!--  <el-table-column prop="good_out_price" label="外卖价" align="center" width="150">
                    </el-table-column> -->
                <!-- </el-table-column> -->

                <el-table-column prop="good_rack" label="上下架" align="center">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.good_rack" active-color="#13ce66" inactive-color="#ff4949" @change="rack(scope.$index, scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                 <el-table-column prop="update_time" label="更新时间" sortable align="center" width="200">
                </el-table-column>
                <el-table-column fixed='right' label="操作" align="center" width="150">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form">
                <!-- <el-form-item label="日期">
                    <el-date-picker type="date" placeholder="选择日期" v-model="form.date" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item> -->
                <!-- <el-form-item label="名称">
                    <el-input v-model="form.good_name"></el-input>
                </el-form-item> -->
                <div class="editD">
                    <label class="editDL">名称</label>
                    <el-input v-model="form.good_name"></el-input>
                </div>
                 <div class="editD">
                     <label class="editDL">图片</label>
                    <el-upload class="avatar-uploader" :action='$gretUrl+"admin/good/upimg"' :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                         <img v-if="form.good_img" :src="form.good_img" class="avatar">
                         <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                     </el-upload>
                </div>
                 <div class="editD">
                    <label class="editDL">分类</label>
                    <!-- <el-input v-model="form.good_type"></el-input> -->
                      <el-select v-model="form.good_type" placeholder="请选择">
                        <el-option v-for="item in typeData" :key="item.type_id" :label="item.type_name" :value="item.type_id" :disabled="item.rack == 1 ?false:true">
                        </el-option>
                      </el-select>
                </div>
                 <div class="editD">
                    <label class="editDL">简介</label>
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="form.good_content"></el-input>
                </div>
                 <div class="editD">
                    <label class="editDL">规格</label>
                    <div>
                        <!-- <div v-for="item in specData" :key="item.type_id"> -->
                            <!-- <div>{{form.good_spec}}</div> -->
                          <el-checkbox-group v-model="form.good_spec">
                            <el-checkbox v-for="item in specData" :label="item.set_id" :key="item.set_name">{{item.set_name}}</el-checkbox>
                          </el-checkbox-group>
                            <!-- <span style="color: #ccc; font-size: 18px;">{{item.set_name}}</span> -->

                            <!-- <el-checkbox-group v-model="">
                                <el-checkbox-button v-for="i in item.info" :label="i.set_type_id" :key="i.set_type_id">{{i.groom ==1 ? '(推荐)' :''}}{{i.set_type_name}}{{i.add_price > 0 ? '+￥'+i.add_price : ''}}</el-checkbox-button>
                            </el-checkbox-group> -->
                        <!-- </div> -->

                    </div>
                    <!-- <el-checkbox-group v-model="form.spec"> -->
                      <!-- <el-checkbox-button v-for="item in specData" :label="item" :key="item">{{item}}</el-checkbox-button> -->
                    <!-- </el-checkbox-group> -->
                </div>
                 <div class="editD">
                    <label class="editDL">堂食价格</label>
                    <el-input-number v-model="form.good_price" :precision="2" :step="0.1" :min="0"></el-input-number>
                </div>
                 <!-- <div class="editD">
                    <label class="editDL">外卖价格</label>
                    <el-input-number v-model="form.good_out_price" :precision="2" :step="0.1"  :min="0"></el-input-number>
                </div> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

     // const cityOptions = ['上海', '北京', '广州', '深圳'];
    export default {
        inject : ['reload'],
        name: 'basetable',
        data() {
            return {
                // url: './static/vuetable.json',
                typeData:[],                    //分类
                specData:[],                    //规格
                tableData: [],
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                editVisible: false,
                delVisible: false,
                
                form: {
                    goods_id:'',
                    update_time: '',
                    good_type: '',
                    good_name: '',
                    good_img:'',
                    good_content:'',
                    good_price: '',
                    good_out_price: '',
                    good_spec:[],
                },
                idx: -1,
                admininfo:JSON.parse(localStorage.getItem('ms_username')),
                total:1,
                title:'',
            }
        },
        created() {
            this.getSpec();
            this.getData();
            this.getType();
        },
        computed: {
            data() {
                return this.tableData.filter((d) => {
                    let is_del = false;
                    for (let i = 0; i < this.del_list.length; i++) {
                        if (d.good_name === this.del_list[i].good_name) {
                            is_del = true;
                            break;
                        }
                    }
                    if (!is_del) {
                        if(d.good_name.indexOf(this.select_word) > -1 ) {
                            return d;
                        }
                    }
                })
            }
        },
        methods: {
              // handleCheckedCitiesChange(value) {
              //   let checkedCount = value.length;
              //   this.checkAll = checkedCount === this.form.good_spec.length;
              //   this.isIndeterminate = checkedCount > 0 && checkedCount < this.form.good_spec.length;
              // },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                this.getData();

            },
            // 获取 easy-mock 的模拟数据
            getData() {
                // 开发环境使用 easy-mock 数据，正式环境使用 json 文件
                // if (process.env.NODE_ENV === 'development') {
                //     this.url = '/ms/table/list';
                // };
                // this.$axios.get(this.url, {
                //     page: this.cur_page
                // }).then((res) => {
                //     this.tableData = res.data.list;
                // })
                // console.log(this.admininfo)
                  this.$axios.get('admin/good', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                        page: this.cur_page
                    }
                }).then((res) => {
                     if(res.data.status == 0){
                            this.tableData = res.data.data.data;
                            this.total = res.data.data.total 
                        }else if(res.data.status == 3){
                           this.$router.push('login') 
                        }
                     // this.form.spec.spec = res.data.data.data[0].spec.spec
                })

            },
            getSpec(){
                this.$axios.get('admin/set/setall', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                    }
                }).then((res) => {
                    // console.log(res.data.data);
                    this.specData = res.data.data;
                     // this.form.spec.spec = res.data.data.data[0].spec.spec
                })
            },
            getType(){
                this.$axios.get('admin/type/all', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                    }
                }).then((res) => {
                    // console.log(res.data.data);
                    this.typeData = res.data.data;
                     // this.form.spec.spec = res.data.data.data[0].spec.spec
                })
            },
            search() {
                this.is_search = true;
                 this.$axios.get('admin/good/search', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                        page:this.cur_page,
                        type:this.select_cate,
                        keyword:this.select_word,
                    }
                }).then((res) => {
                    // console.log(res.data)
                    this.tableData = res.data.data.data;
                    this.total = res.data.data.total;
                    this.select_word='';
                })


            },
            formatter(row, column) {
                return row.address;
            },
            getfor(row,column){
                var roleName = []
                for(var i = 0 ; i < row.roles.length;i++){
                    roleName.push(row.roles[i])
                }
                return roleName.json();
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            add(){
                this.title = '添加'
                this.form = {
                    good_type: '',
                    good_name: '',
                    good_img:'',
                    good_content:'',
                    good_price: '',
                    good_out_price: '',
                    good_spec:[],
                }
                this.editVisible = true;
            },
            handleEdit(index, row) {
                 this.title = '编辑'
                this.idx = index;
                const item = this.tableData[index];
                // console.log(item)
                this.form = {
                    good_id: item.good_id,
                    good_type: item.good_type,
                    good_name: item.good_name,
                    good_img:item.good_img,
                    good_content:item.good_content,
                    good_price: item.good_price,
                    good_out_price: item.good_out_price,
                    good_spec:item.good_spec =='' ? [] : item.good_spec,
                }
                this.editVisible = true;
            },
            handleDelete(index, row) {
                this.idx = index;
                this.delVisible = true;
            },
            delAll() {
                const length = this.multipleSelection.length;
                let str = '';
                this.del_list = this.del_list.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error('删除了' + str);
                this.multipleSelection = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 保存编辑
            saveEdit() {
                // let date = new Date()
      
                //  this.form.update_time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()
                     // console.log(this.form);
                     if(this.form.good_spec.length == 0 ){
                        this.form.good_spec =''
                     }
                 if(this.title == '添加'){
                    // this.tableData.push(this.form)
                    // // this.$set(this.tableData, this.idx, this.form);
                    // this.total = this.tableData.length+1
                    // this.editVisible = false;
                    this.$axios.post('admin/good/add',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        data:this.form
                    }).then((res)=>{
                        if(res.data.status == 0){
                            this.$message.success('添加成功');
                            this.reload()
                        }else{
                             this.$message(res.data.msg);
                        }
                    })
                    

                }else if(this.title == '编辑'){
                    // this.$set(this.tableData, this.idx, this.form);
                    // this.editVisible = false;
                    // this.$message.success(`修改第 ${this.idx+1} 行成功`);
                    // for(var i=0 ; i <= this.form.good_spec.length;i++){
                    //     this.form.good_spec[i] = parseInt(this.form.good_spec[i])
                    // }
                    // console.log(this.form.good_spec[i]);
                    // console.log(this.form.good_spec)
                    this.$axios.post('admin/good/up',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        data:this.form
                    }).then((res)=>{
                        if(res.data.status == 0){
                            this.$message.success(`修改成功`);
                            this.reload()
                        }else{
                             this.$message(res.data.msg);
                        }
                    })

                }
            },
            // 确定删除
            deleteRow(){

                // this.tableData.splice(this.idx, 1);
                // this.$message.success('删除成功');
                // this.delVisible = false;
                this.$axios.post('admin/good/del',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        good_id:this.tableData[this.idx].good_id
                    }).then((res)=>{
                        if(res.data.status == 0){
                            this.$message.success('删除成功');
                            this.reload()
                        }else{
                             this.$message(res.data.msg);
                        }
                    })


            },
            formatSpec(row,column){
                var str = '';
                if(row.good_spec == ''){
                    str = ''
                }else{
                    // for (var i = 0; i < row.good_spec.length; i++) {
                    //     str += row.good_spec[i].name+":"
                    // }
                    str =  row.good_spec
                }
                return str;
            },
             // 头像上传
             handleAvatarSuccess(res, file) {
                console.log(res);
                // this.imageUrl = URL.createObjectURL(file.raw);
                this.form.good_img = res.data.data.src
              },
              beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                  this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                  this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
              },
             rack(index,row){
                // console.log(index)

                // this.tableData[index].good_id
                 this.$axios.post('admin/good/rack',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        good_id:this.tableData[index].good_id
                    }).then((res)=>{
                        if(res.data.status == 0){
                            this.$message.success('修改成功');
                            // this.reload()
                        }else if(res.data.status == 30){
                            this.tableData[index].good_rack = false
                             this.$message(`${res.data.msg},该分类没有上架`);
                        }else{
                             this.$message.error(res.data.msg);
                        }
                    })

              }
        }
    }

</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .table{
        width: 100%;
        font-size: 14px;
    }
    .red{
        color: #ff0000;
    }
     /*头像框*/
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 180px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  /*排版*/
  .editD{
    display: flex; margin-bottom: 18px;
  }
  .editDL{
    flex: 0 0 100px;text-align: center;line-height: 32px;
  }
  .el-checkbox{
    margin: 0 30px 0 0;
  }
  .el-checkbox+.el-checkbox{
    margin-left: 0; 
  }
  .good_spec{
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow:ellipsis;
  }
</style>
